package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.apiResult.Result;
import com.ruoyi.common.apiResult.ZhtcRe;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.CommonUtil;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.core.page.PagePlus;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.system.aikeService.ToZhtcApiService;
import com.ruoyi.system.apiQuery.AddOnlineMonthTicketQuery;
import com.ruoyi.system.apiService.HomeParkService;
import com.ruoyi.system.domain.ZsyyParkTicketType;
import com.ruoyi.system.mapper.ZsyyParkMapper;
import com.ruoyi.system.mapper.ZsyyParkTicketTypeMapper;
import com.ruoyi.system.vo.DownloadParkTicketVo;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.common.core.mybatisplus.core.ServicePlusImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.system.bo.ZsyyParkTicketAddBo;
import com.ruoyi.system.bo.ZsyyParkTicketQueryBo;
import com.ruoyi.system.bo.ZsyyParkTicketEditBo;
import com.ruoyi.system.domain.ZsyyParkTicket;
import com.ruoyi.system.mapper.ZsyyParkTicketMapper;
import com.ruoyi.system.vo.ZsyyParkTicketVo;
import com.ruoyi.system.service.IZsyyParkTicketService;
import com.ruoyi.system.mapper.ZsyyParkTicketMapper;

import java.util.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

/**
 * 月票管理Service业务层处理
 *
 * @author wangghua
 * @date 2021-07-14
 */
@Service
public class ZsyyParkTicketServiceImpl extends ServicePlusImpl<ZsyyParkTicketMapper, ZsyyParkTicket> implements IZsyyParkTicketService {
	protected Log logger = LogFactory.getLog(this.getClass());
    @Autowired
    private ZsyyParkTicketMapper ticketMapper;
    @Autowired
    private ZsyyParkTicketTypeMapper ticketTypeMapper;
    @Autowired
    private ZsyyParkServiceImpl parkService;
	@Resource
	private ToZhtcApiService toZhtcApiService;
	@Resource
	private HomeParkService homeParkService;

    @Override
    public ZsyyParkTicketVo queryById(Long id){
        return getVoById(id, ZsyyParkTicketVo.class);
    }

    @Override
    public TableDataInfo<ZsyyParkTicketVo> queryPageList(ZsyyParkTicketQueryBo bo) {
        PagePlus<ZsyyParkTicket, ZsyyParkTicketVo> result = pageVo(PageUtils.buildPagePlus(), buildQueryWrapper(bo), ZsyyParkTicketVo.class);
        return PageUtils.buildDataInfo(result);
    }

    @Override
    public List<ZsyyParkTicketVo> queryList(ZsyyParkTicketQueryBo bo) {
        return listVo(buildQueryWrapper(bo), ZsyyParkTicketVo.class);
    }

    private LambdaQueryWrapper<ZsyyParkTicket> buildQueryWrapper(ZsyyParkTicketQueryBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ZsyyParkTicket> lqw = Wrappers.lambdaQuery();
        lqw.like(StrUtil.isNotBlank(bo.getCarNo()), ZsyyParkTicket::getCarNo, bo.getCarNo());
		lqw.orderByDesc(ZsyyParkTicket::getCreatetime);
        return lqw;
    }

    @Override
    public AjaxResult insertByAddBo(ZsyyParkTicketAddBo parkTicket) {
		Result result = new Result();
		List<ZsyyParkTicket> list = ticketMapper.getParkTicketByCarNo(parkTicket.getCarNo());
		if(list.size()>0){
			return AjaxResult.error("该车牌号已添加过，不能重复添加！");
		}
		ZsyyParkTicketType ticketType = ticketTypeMapper.getTicketType(parkTicket.getMonthTicketConfigId());
		Map toTicket = new HashMap();
		toTicket.put("carNo",parkTicket.getCarNo());
		toTicket.put("billCode","msdw"+ DateUtil.format(new Date(),"yyyyMMddHHmmss"));
		toTicket.put("parkCodes",ticketType.getParkCodes());
		toTicket.put("originPrice",ticketType.getPrice());
		toTicket.put("favorPrice",parkTicket.getFavorPrice());
		toTicket.put("payMode",4);
		toTicket.put("payModeRemark","线下支付");
		toTicket.put("payOrigin",7);
		toTicket.put("payOriginRemark",parkTicket.getPayOriginRemark());
		toTicket.put("userName",parkTicket.getUserName());
		toTicket.put("userPhone", StringUtils.isEmpty(parkTicket.getUserPhone())?"13123456789":parkTicket.getUserPhone());
		toTicket.put("monthTicketConfigId",ticketType.getMonthTicketConfigId());
		List timePeriodList = new ArrayList();
		Map timePeriod = new HashMap();
		timePeriod.put("startTime", DateUtil.format(parkTicket.getStartTime(),"yyyy-MM-dd HH:mm:ss"));
		timePeriod.put("endTime",DateUtil.format(parkTicket.getEndTime(),"yyyy-MM-dd HH:mm:ss"));
		timePeriodList.add(timePeriod);
		toTicket.put("timePeriodList",timePeriodList);
		Map redata = null;
		String toTicketStr = JSON.toJSONString(toTicket);
		if(ticketType.getParkCodes().indexOf("/")==-1){
			if(parkTicket.getId() !=null){
				ZsyyParkTicket parkTicket1 = ticketMapper.selectById(parkTicket.getId());
				if(parkTicket1.getCarNo().equals(parkTicket.getCarNo())&&parkTicket1.getMonthTicketConfigId()==parkTicket.getMonthTicketConfigId()){
					String data = toZhtcApiService.privateApi("renewOnlineVipTicket", toTicketStr,null);
					redata = JSON.parseObject(data,Map.class);

				}else{
					Map toTicket1 = new HashMap();
					toTicket1.put("carNo",parkTicket1.getCarNo());
					toTicket1.put("billCode","msdw"+DateUtil.format(new Date(),"yyyyMMddHHmmss"));
					toTicket1.put("parkCode",parkTicket1.getParkCodes());
					toTicket1.put("monthTicketId",parkTicket1.getMonthTicketId());
					toTicket1.put("refundPrice",0);
					toTicket1.put("payMode",4);
					toTicket1.put("payModeRemark","线下取消");
					toTicket1.put("payOrigin",7);
					String toTicketStr1 = JSON.toJSONString(toTicket1);
					//先取消月票
					toZhtcApiService.privateApi("cancelOnlineVipTicket", toTicketStr1,null);
					//添加月票
					String data = toZhtcApiService.privateApi("addOnlineMonthTicket", toTicketStr,null);
					redata = JSON.parseObject(data,Map.class);
				}

			}else{
				String data = toZhtcApiService.privateApi("addOnlineMonthTicket", toTicketStr,null);
				redata = JSON.parseObject(data,Map.class);
			}

		}else{
			AddOnlineMonthTicketQuery query = JSON.parseObject(toTicketStr, AddOnlineMonthTicketQuery.class);
			if(parkTicket.getId() !=null ){
				query.setID(parkTicket.getMonthTicketId());
				query.setAction("edit");
			}else {
				query.setAction("add");
			}
			ZhtcRe re = homeParkService.addOnlineMonthTicket(query);
			redata = JSON.parseObject(JSON.toJSONString(re),Map.class);
		}
		if("业务成功".equals(redata.get("message"))){
			Map data1 = (Map)redata.get("data");
			ZsyyParkTicket parkt = JSON.parseObject(toTicketStr,ZsyyParkTicket.class);
//			BeanUtil.copyPropertiesIgnoreNull(parkt,parkTicket);
			ZsyyParkTicket add = BeanUtil.toBean(parkt, ZsyyParkTicket.class);
			add.setStartTime(parkTicket.getStartTime());
			add.setEndTime(parkTicket.getEndTime());
			add.setMonthTicketId(Long.parseLong(data1.get("monthTicketId").toString()));
			add.setParkCodes(ticketType.getParkCodes());
			if(parkTicket.getId()==null){
				ticketMapper.insert(add);//添加
				result.setMessage(Result.Code.SUCCESS, "添加成功！");
				if("2KST6MLE".equals(ticketType.getParkCodes())){
					parkService.addHeiheTicket(add,"TDZN/100760P5757");
				}
				parkTicket.setId(null);
			}


		}else {
			return AjaxResult.error("远程添加月票失败");
		}
        return AjaxResult.success("添加成功");
    }

    @Override
    public AjaxResult updateByEditBo(ZsyyParkTicketEditBo bo) {
		Result result = new Result();
		ZsyyParkTicket parkTicket1 = ticketMapper.selectById(bo.getId());
		if(!parkTicket1.getCarNo().equals(bo.getCarNo())){
			List<ZsyyParkTicket> list = ticketMapper.getParkTicketByCarNo(bo.getCarNo());
			if(list.size()>0){
				return AjaxResult.error("不能把车牌改为已有的车牌");
			}
		}
		bo.setUpdatetime(new Date());  //更新
		if("2KST6MLE".equals(bo.getParkCodes())){
			parkService.addHeiheTicket(parkTicket1,"TDZN/100760P5757");
		}
        ZsyyParkTicket update = BeanUtil.toBean(bo, ZsyyParkTicket.class);
        validEntityBeforeSave(update);
        updateById(update);
        return AjaxResult.success("修改成功");
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(ZsyyParkTicket entity){
        //TODO 做一些数据校验,如唯一约束
    }

    @Override
    public AjaxResult deleteWithValidByIds(Collection<Long> ids) {
		AjaxResult result = new AjaxResult();
		try {
			for (Long id:ids) {
				ZsyyParkTicket parkTicket = ticketMapper.selectById(id);
				Map toTicket = new HashMap();
				toTicket.put("carNo",parkTicket.getCarNo());
				toTicket.put("billCode","msdw"+DateUtil.format(new Date(),"yyyyMMddHHmmss"));
				toTicket.put("parkCode",parkTicket.getParkCodes());
				toTicket.put("monthTicketId",parkTicket.getMonthTicketId());
				toTicket.put("refundPrice",0);
				toTicket.put("payMode",4);
				toTicket.put("payModeRemark","线下取消");
				toTicket.put("payOrigin",7);
				Map redata = null;
				String toTicketStr = JSON.toJSONString(toTicket);
				if(parkTicket.getParkCodes().indexOf("/")==-1){
					String data = toZhtcApiService.privateApi("cancelOnlineVipTicket", toTicketStr,null);
					redata = JSON.parseObject(data,Map.class);
					if("2KST6MLE".equals(parkTicket.getParkCodes())&&parkTicket.getMqttCarId()!=null){
						homeParkService.cancelOnlineVipTicket(parkTicket.getMqttCarId(),"TDZN/100760P5757");
					}
				}else{
					ZhtcRe re = homeParkService.cancelOnlineVipTicket(parkTicket.getMonthTicketId(),parkTicket.getParkCodes());
					redata = JSON.parseObject(JSON.toJSONString(re),Map.class);
				}
				if("业务成功".equals(redata.get("message"))){
					ticketMapper.deleteById(id);
				}else {
					result.setMsg( "远程删除月票失败！");
					result.setCode(500);
					return result;
				}
				result.setCode(200);
			}

		}catch (Exception e){
			e.printStackTrace();
			AjaxResult.error("删除失败");
		}
		return result;
    }

	@Override
	public String importParkTicket(List<DownloadParkTicketVo> ticketVoList, boolean updateSupport, String operName) {
		if (Validator.isNull(ticketVoList) || ticketVoList.size() == 0) {
			throw new CustomException("导入数据不能为空！");
		}
		int successNum = 0;
		int failureNum = 0;
		StringBuilder successMsg = new StringBuilder();
		StringBuilder failureMsg = new StringBuilder();
		for (DownloadParkTicketVo ticketVo : ticketVoList) {
			try {
				// 验证是否存在这个车牌
				QueryWrapper wrapper = new QueryWrapper();
				wrapper.eq("car_no",ticketVo.getCarNo());
				ZsyyParkTicket parkTicket = baseMapper.selectOne(wrapper);
				//比较时间大小
				if (Validator.isNull(parkTicket)
					&& CommonUtil.compareTime(ticketVo.getStartTime(),ticketVo.getEndTime())
					&& !CommonUtil.isEmpty(ticketVo.getMonthTicketConfigId())
					&& !CommonUtil.isEmpty(ticketVo.getCarNo())
				) {
					successNum++;
					successMsg.append("<br/>" + successNum + "、车牌号 " + ticketVo.getCarNo() + " 导入成功");

					ZsyyParkTicketAddBo add = BeanUtil.toBean(ticketVo, ZsyyParkTicketAddBo.class);
					this.insertByAddBo(add);//插入到数据库
				}  else if (updateSupport) {
					ZsyyParkTicket add = BeanUtil.toBean(ticketVo, ZsyyParkTicket.class);
					add.setId(parkTicket.getId());
					baseMapper.updateById(add);
					successNum++;
					successMsg.append("<br/>" + successNum + "、车牌号 " + ticketVo.getCarNo() + " 更新成功");
				} else {
					failureNum++;
					failureMsg.append("<br/>" + failureNum + "、车牌号 " + ticketVo.getCarNo()+ " 已存在");
				}

			} catch (Exception e) {
				failureNum++;
				String msg = "<br/>" + failureNum + "、车牌号 " + ticketVo.getCarNo()  + " 导入失败：";
				failureMsg.append(msg + e.getMessage());
				logger.error(msg, e);
			}
		}
		if (failureNum > 0) {
			failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
			throw new CustomException(failureMsg.toString());
		} else {
			successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
		}
		return successMsg.toString();
	}
}
